import {Toast} from 'vant'
import ExamApi from '../../../repo/api/LoginAPI'
export {applyPageModule}


const _hasErrorMobile = mobile => {
  return !(mobile && mobile.length === 11 && mobile.startsWith('1'))
}
/* mobile为参数 手机号码是否长度为11并且以1开头 */

let countdownHandler = undefined
const applyPageModule = {
  namespaced: true,

  state: {
    authState: 'init',
    authTips: '获取验证码',
    countdown: 0,
  },
  getters: {
    btnAuth:(state) => {
      let authState = state.authState
      if (authState === 'init') {
        return '获取验证码'
      }
      if (authState === 'retry') {
        return '获取验证码'
      } else if(state.countdown < 10){
        // authState === 'counting'
        return `重新获取 0${state.countdown}s`
        // 秒数
      }else{
        return `重新获取 ${state.countdown}s`
      }
    },
  },
  mutations:{
    setAuthState (state, data) {
      state.authState = data
    },
    setCountdown (state, data) {
      state.countdown = data
    },
  },
  actions: {
    getAuthCode({state, commit}, data) {
      if (state.authState === 'counting') return

      if (_hasErrorMobile(data.mobile)) {
        return Toast('请输入正确的手机号码')
      }
      /* 设置setAuthState开始计数 */
      console.log(data.mobile)
      /* 获取验证码接口 */
      commit('setAuthState', 'counting')
       return ExamApi.getAuthCode(data.mobile).then(result => {
          Toast('发送成功')
         }).catch((e) => {
           console.log(e)
         })
    },

    startCountdown({state, commit}) {
      if (state.countdown > 0) return
      //countdown = 0时才startCountDown
      if (countdownHandler) return
      commit('setCountdown', 60)
      countdownHandler = setInterval(() => {
        if (state.countdown > 0) {
          commit('setCountdown', state.countdown - 1)
        } else {
          commit('setAuthState', 'retry')
          clearInterval(countdownHandler)//清除定时器
          countdownHandler = null
        }
      }, 1000) //1秒执行一次
    },
  }
}
